/**
 * 
 */
package org.jms.examples.ibmmq.p2p;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;

import com.ibm.mq.jms.MQQueue;
import com.ibm.mq.jms.MQQueueConnection;
import com.ibm.mq.jms.MQQueueConnectionFactory;
import com.ibm.mq.jms.MQQueueReceiver;
import com.ibm.mq.jms.MQQueueSession;

/**
 * @author Sudarsan
 *
 */
public class Recevier {

	private MQQueueConnectionFactory factory = null;
	private MQQueueConnection connection = null;
	private MQQueue queue = null;
	private MQQueueSession session = null;
	private MQQueueReceiver receiver = null;

	/**
	 * @param args
	 */

	public void readMessage() {

		try {
			factory = new MQQueueConnectionFactory();
			factory.setPort(1415);
			factory.setQueueManager("JMSDEMO");
			factory.setChannel("SYSTEM.DEF.SVRCONN");

			connection = (MQQueueConnection) factory.createQueueConnection();
			session = (MQQueueSession) connection.createQueueSession(false,
					MQQueueSession.AUTO_ACKNOWLEDGE);
			queue = (MQQueue) session.createQueue("JMSDEMO.QL");
			receiver = (MQQueueReceiver) session.createReceiver(queue);

			connection.start();

			Message objectMessage = receiver.receive();
			if (objectMessage instanceof ObjectMessage) {
				Object object = ((ObjectMessage) objectMessage).getObject();
				Product product = (Product) object;
				System.out.println(product);
			}

			// TextMessage message = (TextMessage) receiver.receive();
			// System.out.println("The Message is : " + message.getText());

		} catch (JMSException e) {
			e.printStackTrace();
		} finally {
			if (receiver != null) {
				try {
					receiver.close();
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
			if (session != null) {
				try {
					session.close();
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
			if (connection != null) {
				try {
					connection.close();
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static void main(String[] args) {
		Recevier recevier = new Recevier();
		recevier.readMessage();
	}

}
